﻿#include "patternselectwidget.h"
#include "ui_patternselectwidget.h"

PatternSelectWidget::PatternSelectWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PatternSelectWidget),
    m_itemPerPage(10)
{
    ui->setupUi(this);
    setWindowFlags (Qt::Window | Qt::FramelessWindowHint);
    setWindowModality(Qt::ApplicationModal);

    m_mousePressX = 0;
    m_mousePressY = 0;
    m_mouseReleaseX = 0;
    m_mouseReleaseY = 0;

    this->move(0+g_mainWidgetPos.x(),0+g_mainWidgetPos.y());
    initControl();
    initialize();
}

PatternSelectWidget::~PatternSelectWidget()
{
    delete ui;
}

//初始化窗体控件，包括位置、尺寸、样式
void PatternSelectWidget::initControl()
{
    m_imageButtonList.clear();
    m_imageButtonList.append(ui->buttonImage1);
    m_imageButtonList.append(ui->buttonImage2);
    m_imageButtonList.append(ui->buttonImage3);
    m_imageButtonList.append(ui->buttonImage4);
    m_imageButtonList.append(ui->buttonImage5);
    m_imageButtonList.append(ui->buttonImage6);
    m_imageButtonList.append(ui->buttonImage7);
    m_imageButtonList.append(ui->buttonImage8);
    m_imageButtonList.append(ui->buttonImage9);
    m_imageButtonList.append(ui->buttonImage10);

    //根据不同分辨率设置控件的位置和尺寸
    initResolution();
    initControlStyle();//初始化窗体控件样式
}

//初始化窗体控件为任意分辨率
void PatternSelectWidget::initResolution()
{
    double factoryX = getFactoryX();
    double factoryY = getFactoryY();

    this->resize(GLB_SCR_WIGHT*factoryX,GLB_SCR_HEIGHT*factoryY);
    ui->frameBack->setGeometry(0*factoryX,0*factoryY,GLB_SCR_WIGHT*factoryX,GLB_SCR_HEIGHT*factoryY);
    ui->buttonTypeLogo->setGeometry(GLB_EDGE_WIGHT*factoryX,GLB_EDGE_HEIGHT*factoryY,GLB_LICON_SIZE*factoryX,GLB_LICON_SIZE*factoryY);
    ui->labelMainTitle->setGeometry((GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT)*factoryX,GLB_EDGE_HEIGHT*factoryY,
                                    (GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT*2))*factoryX,GLB_TEXT_L_HEIGHT*factoryY);
    ui->labelSubTitle->setGeometry((GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT+GLB_TAB_WIGHT)*factoryX,(GLB_EDGE_HEIGHT+GLB_LICON_SIZE-GLB_TEXT_HEIGHT)*factoryY,
                                   (GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_LICON_SIZE+GLB_EDGE_WIGHT+GLB_TAB_WIGHT*2))*factoryX,GLB_TEXT_HEIGHT*factoryY);

    ui->frameImage->setGeometry(27*factoryX,108*factoryY,1000*factoryX,431*factoryY);

    //预览图片
    QRect rectImage(18*factoryX,9*factoryY,120*factoryX,120*factoryY);
    QRect rectName(24*factoryX,140*factoryY,120*factoryX,42*factoryY);
    for(int i = 0; i < 2; i++)
    {
        s16 num = m_imageButtonList.size()/2;
        for(int j = 0; j < num; j++)
        {
            m_imageButtonList.at(i*num + j)->setGeometry((25+j*190)*factoryX,(8+i*208)*factoryY,158*factoryX,190*factoryY);
            m_imageButtonList.at(i*num + j)->initUpImageDownName(rectImage,rectName);
        }
    }
    ui->frameRightUp->setGeometry(0*factoryX,(GLB_EDGE_HEIGHT+GLB_LICON_SIZE-GLB_MICON_SIZE)*factoryY,GLB_SCR_WIGHT*factoryX,GLB_MICON_SIZE*factoryY);
    ui->buttonBackUpDir->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_MICON_SIZE))*factoryX,0*factoryY,GLB_MICON_SIZE*factoryX,GLB_MICON_SIZE*factoryY);

    //label样式
    ui->labelMainTitle->setFont(fontSize_L());
    ui->labelMainTitle->setStyleSheet(titleTextColour());
    ui->labelSubTitle->setFont(fontSize_M());
    ui->labelSubTitle->setStyleSheet(noteTextColour());
    ui->labelPageNum->setFont(fontSize_M());
    ui->labelPageNum->setStyleSheet(titleTextColour());

    //    ui->frameInfo1->setGeometry(1528,210,328,284);
    ui->frameInfo1->hide();                 //屏蔽右侧状态栏

    QList<QLabel*> labelList1;
    labelList1.append(ui->labelPatternName);
    labelList1.append(ui->labelTotalNeedle);
    labelList1.append(ui->labelPatternWidth);
    labelList1.append(ui->labelPatternHeight);
    labelList1.append(ui->labelX);
    labelList1.append(ui->labelY);
    for(int i = 0; i < labelList1.size(); i++)
    {
        labelList1[i]->setGeometry(5*factoryX,(i*26)*factoryY,90*factoryX,32*factoryY);
        labelList1[i]->setFont(fontSize_M());
        labelList1[i]->setStyleSheet(titleTextColour());
    }

    QList<QLabel*> labelList2;
    labelList2.append(ui->labelPatternNameValue);
    labelList2.append(ui->labelTotalNeedleValue);
    labelList2.append(ui->labelPatternWidthValue);
    labelList2.append(ui->labelPatternHeightValue);
    labelList2.append(ui->labelXValue);
    labelList2.append(ui->labelYValue);
    for(int i = 0; i < labelList2.size(); i++)
    {
        labelList2[i]->setGeometry(42*factoryX,(i*26)*factoryY,140*factoryX,32*factoryY);
        labelList2[i]->setFont(fontSize_M());
        labelList2[i]->setStyleSheet(titleTextColour());
    }

    ui->framePageBtn->setGeometry(0*factoryX,(GLB_SCR_HEIGHT-GLB_LBUT_HEIGHT-GLB_EDGE_WIGHT)*factoryY,GLB_SCR_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->labelPageNum->setGeometry(GLB_EDGE_WIGHT*factoryX,(GLB_SCR_HEIGHT-GLB_TEXT_HEIGHT-GLB_EDGE_WIGHT)*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_TEXT_HEIGHT*factoryY);
    ui->buttonPgUp->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*3+GLB_LBUT_WIGHT*4))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->buttonPgDn->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*2+GLB_LBUT_WIGHT*3))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->buttonOk->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*1+GLB_LBUT_WIGHT*2))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
    ui->buttonCancel->setGeometry((GLB_SCR_WIGHT-(GLB_EDGE_WIGHT+GLB_BAS_WIGHT*0+GLB_LBUT_WIGHT*1))*factoryX,0*factoryY,GLB_LBUT_WIGHT*factoryX,GLB_LBUT_HEIGHT*factoryY);
}

//初始化窗体控件样式
void PatternSelectWidget::initControlStyle()
{
    SetStyle setControlStyle;
    setControlStyle.setUiName(this->objectName());

    //背景图
    QString frameBackImgPath = setControlStyle.getStyleSheet(this->objectName());
    ui->frameBack->setStyleSheet(frameBackImgPath);

    //frame样式
    ui->framePageBtn->setStyleSheet(transparentStyle());
    ui->frameImage->setStyleSheet(transparentStyle());
    ui->frameInfo1->setStyleSheet(transparentStyle());
    ui->frameRightUp->setStyleSheet(transparentStyle());

    //条目
    for(int i = 0; i < m_itemPerPage; i++)
    {
        m_imageButtonList[i]->setCheckedBottomImage(setControlStyle.getBottomStyleSheet(m_imageButtonList[i]->parent()->objectName()));
        m_imageButtonList[i]->setLabelFont(fontSize_M());
    }

    ui->buttonBackUpDir->setStyleSheet(backIconStyle());;
    ui->buttonBackUpDir->setTopImage(setControlStyle.getTopStyleSheet(ui->buttonBackUpDir->objectName()));

    //四个按钮样式表一样
    ui->buttonPgUp->setStyleSheet(confirmIconStyle());
    ui->buttonPgUp->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonPgUp->objectName()),12);

    ui->buttonPgDn->setStyleSheet(confirmIconStyle());
    ui->buttonPgDn->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonPgDn->objectName()),12);

    ui->buttonOk->setStyleSheet(confirmIconStyle());
    ui->buttonOk->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonOk->objectName()),12);

    ui->buttonCancel->setStyleSheet(confirmIconStyle());
    ui->buttonCancel->setTopImage(setControlStyle.getSharedTopStyleSheet(ui->buttonCancel->objectName()),12);
}

//初始化
void PatternSelectWidget::initialize()
{
    m_firstFilePath.clear();
    m_curFilePath.clear();
    m_fileItemList.clear();

    m_curPages = 1;//花样选择界面当前页数
    m_pageNums = 1;//总页数
    m_selectedPattenIdx = -1;//被选中的花版号

    initPattern();
}

//初始化花样
void PatternSelectWidget::initPattern()
{
    //花样文件目录
    QDir apppath(qApp->applicationDirPath());
    QString filePath = apppath.path() + apppath.separator() + PATTERNPATH;
    m_firstFilePath = QDir(filePath).absolutePath();//为了将"\"变为"/"
    getDirPatternFiles(m_firstFilePath);
}

//获取花样文件下的路径或者花样
void PatternSelectWidget::getDirPatternFiles(QString dirPath)
{
    m_curFilePath = dirPath;//记录当前目录
    if(m_curFilePath == m_firstFilePath)//如果当前目录为一级目录
    {
        ui->buttonBackUpDir->setEnabled(false);//设置按钮不可按(返回上级目录按钮)
    }
    else
    {
        ui->buttonBackUpDir->setEnabled(true);//设置按钮可按(返回上级目录按钮)
    }

    QString desiredPath = dirPath; // 原始路径
    // 查找关键路径节点位置
    int dataPos = dirPath.indexOf("/datafiles");
    if (dataPos != -1) {
        // 截取并替换斜杠
        desiredPath = dirPath.mid(dataPos + 10)
                .replace("/", " > "); // 关键替换操作
    }
    ui->labelSubTitle->setText(tr("Pattern setting > Pattern selection") + desiredPath);

    createCurDirPatterns();
}
//刷新界面显示
void PatternSelectWidget::refreshPageUi()
{
    int itemNum;
    if (m_fileItemList.size() <= 0)
    {
        itemNum = 0;

        for (int i = 0; i < m_itemPerPage; i++)
        {
            m_imageButtonList.at(i)->hide();
        }
        ui->labelPageNum->setText(tr("PageNum: 0/0"));//页数: 0/0
        ui->buttonPgUp->setEnabled(false);
        ui->buttonPgDn->setEnabled(false);
        ui->buttonOk->setEnabled(false);

        clearFileInfo();
        return;
    }
    else
    {
        itemNum = m_fileItemList.size();
    }

    m_pageNums = (itemNum + m_itemPerPage - 1)/m_itemPerPage;// 计算页数
    if (m_curPages > m_pageNums)// 当前页
    {
        m_curPages = m_pageNums;
    }
    if (m_curPages <= 1)
    {
        m_curPages = 1;
    }

    int itemidx = (m_curPages - 1) * m_itemPerPage;

    for (int i = 0; i < m_itemPerPage; i++)
    {
        if (itemidx < itemNum)
        {
            QImage image = m_fileItemList.at(itemidx).getPreviewImage();
            m_imageButtonList[i]->setPreviewImage(image);
            m_imageButtonList[i]->setLabelName(m_fileItemList.at(itemidx).getShowInfo());
            m_imageButtonList.at(i)->show();

            itemidx++;
        }
        else
        {
            m_imageButtonList.at(i)->hide();
        }
    }

    // 翻页按钮
    if (m_curPages <= 1)
    {
        ui->buttonPgUp->setEnabled(false);
    }
    else
    {
        ui->buttonPgUp->setEnabled(true);
    }
    if (m_curPages >= m_pageNums)
    {
        ui->buttonPgDn->setEnabled(false);
    }
    else
    {
        ui->buttonPgDn->setEnabled(true);
    }

    // 页信息
    if(m_pageNums == 0)
    {
        m_curPages = 0;
    }

    // 页信息
    QString str = tr("pageNum: ") + QString("%1/%2").arg(m_curPages).arg(m_pageNums);//页数:
    ui->labelPageNum->setText(str);

    //refreshCheckedPage();
    refreshChecked();
}

//刷新条目选中状态
void PatternSelectWidget::refreshCheckedPage()
{
    int num =m_fileItemList.size();
    if (num <= m_selectedPattenIdx)//没有花版 num = 0
    {
        m_selectedPattenIdx = -1;
    }

    if(m_selectedPattenIdx == -1)//被选中的花版号初始化的时候就是-1
    {
        clearFileInfo();//清空花样信息
        ui->buttonOk->setEnabled(false);
    }
    else
    {
        ui->buttonOk->setEnabled(true);
    }

    // 刷新页面中被选择的条目
    for(int var = 0; var < m_itemPerPage; var++)//var < 花样选择界面每页图片数
    {
        int idx = (m_curPages - 1) * (m_itemPerPage) + var;
        if(m_selectedPattenIdx == idx)//选中的花版号等于 idx
        {
            QString filePath = m_fileItemList.at(m_selectedPattenIdx).getFilePath();//m_fileItemList 花样列表，从0开始
            QFileInfo file(filePath);
            if(file.isDir())//为文件夹
            {
                m_selectedPattenIdx = -1;
                getDirPatternFiles(filePath);
                return;
            }

            //所选文件
            QString ext = file.suffix().toUpper();
            getFileInfo(filePath,ext);//获取花样信息

            // 条目被选中
            m_imageButtonList.at(var)->setCheckable(true);
            m_imageButtonList.at(var)->setChecked(true);
        }
        else
        {
            // 不被选中
            m_imageButtonList.at(var)->setChecked(false);
            m_imageButtonList.at(var)->setCheckable(false);
        }
    }
}

void PatternSelectWidget::refreshChecked()
{
    int num =m_fileItemList.size();
    if (num <= m_selectedPattenIdx)//没有花版 num = 0
    {
        m_selectedPattenIdx = -1;
    }

    if(m_selectedPattenIdx == -1)//被选中的花版号初始化的时候就是-1
    {
        clearFileInfo();//清空花样信息
        ui->buttonOk->setEnabled(false);
    }
    else
    {
        ui->buttonOk->setEnabled(true);
    }

    // 刷新页面中被选择的条目
    for(int var = 0; var < m_itemPerPage; var++)//var < 花样选择界面每页图片数
    {
        int idx = (m_curPages - 1) * (m_itemPerPage) + var;
        if(m_selectedPattenIdx == idx)//选中的花版号等于 idx
        {
            QString filePath = m_fileItemList.at(m_selectedPattenIdx).getFilePath();//m_fileItemList 花样列表，从0开始
            QFileInfo file(filePath);
            if(file.isDir())//为文件夹
            {
                m_selectedPattenIdx = -1;
                getDirPatternFiles(filePath);
                return;
            }

            // 条目被选中
            m_imageButtonList.at(var)->setCheckable(true);
            m_imageButtonList.at(var)->setChecked(true);
        }
        else
        {
            // 不被选中
            m_imageButtonList.at(var)->setChecked(false);
            m_imageButtonList.at(var)->setCheckable(false);
        }
    }
}

//点击花样图片
void PatternSelectWidget::clickItem(int idx)
{
    if(m_fileItemList.size() <= 0)
    {
        return;
    }
    m_selectedPattenIdx = (m_curPages - 1) * m_itemPerPage + idx - 1;
    refreshCheckedPage();
}

//清空花样信息
void PatternSelectWidget::clearFileInfo()
{
    ui->labelPatternHeightValue->clear();
    ui->labelPatternNameValue->clear();
    ui->labelPatternWidthValue->clear();
    ui->labelTotalNeedleValue->clear();
    ui->labelXValue->clear();
    ui->labelYValue->clear();
}

//获取花样信息
void PatternSelectWidget::getFileInfo(QString filePath, QString suffix)
{
    QFileInfo file(filePath);
    QString fileName = file.fileName();
    int size = fileName.length();
    if(size > NAMEMAXLENGTH)//花样名称过长时截取
    {
        fileName = fileName.mid(0,NAMEMAXLENGTH) + "~";
    }

    if(suffix == "DST")//dst文件
    {
        //qDebug()<<"dst click begin";

        DataFileDst dst;
        dst.initFile(filePath);

        //qDebug()<<"dst.convertDataToAbs() begin";
        dst.convertDataToAbs();
        //qDebug()<<"dst.convertDataToAbs() end";

        ui->labelPatternNameValue->setText(fileName);
        ui->labelTotalNeedleValue->setText(QString::number(dst.getStitchNums()));

        double width = dst.getDatWidth()*0.01;
        ui->labelPatternWidthValue->setText(QString("%1").arg(width));

        double height = dst.getDatHeight()*0.01;
        ui->labelPatternHeightValue->setText(QString("%1").arg(height));

        double maxX = dst.getMaxX()*0.01;
        double minX = dst.getMinX()*0.01;
        ui->labelXValue->setText(QString("(%1,%2)").arg(maxX).arg(minX));

        double maxY = dst.getMaxY()*0.01;
        double minY = dst.getMinY()*0.01;
        ui->labelYValue->setText(QString("(%1,%2)").arg(maxY).arg(minY));

        //qDebug()<<"showfileinfo end";
    }
    else if(suffix == "DSR")//dsr文件
    {
        //
        DataFileDsr dsr;
        dsr.initFile(filePath);
        dsr.convertDataToEmbAbs();
        ui->labelPatternNameValue->setText(fileName);
        ui->labelTotalNeedleValue->setText(QString::number(dsr.getStitchNums()));

        double width = dsr.getDatWidth()*0.01;
        ui->labelPatternWidthValue->setText(QString("%1").arg(width));

        double height = dsr.getDatHeight()*0.01;
        ui->labelPatternHeightValue->setText(QString("%1").arg(height));

        double maxX = dsr.getMaxX()*0.01;
        double minX = dsr.getMinX()*0.01;
        ui->labelXValue->setText(QString("(%1,%2)").arg(maxX).arg(minX));

        double maxY = dsr.getMaxY()*0.01;
        double minY = dsr.getMinY()*0.01;
        ui->labelYValue->setText(QString("(%1,%2)").arg(maxY).arg(minY));
    }
    else if(suffix == "QUI")
    {
        DataFileQui qui;
        qui.initFile(filePath);
        qui.convertDataToEmbAbs();

        ui->labelPatternNameValue->setText(fileName);
        ui->labelTotalNeedleValue->setText(QString::number(qui.getStitchNums()));

        double width = qui.getDatWidth()*0.01;
        ui->labelPatternWidthValue->setText(QString("%1").arg(width));

        double height = qui.getDatHeight()*0.01;
        ui->labelPatternHeightValue->setText(QString("%1").arg(height));

        double maxX = qui.getMaxX()*0.01;
        double minX = qui.getMinX()*0.01;
        ui->labelXValue->setText(QString("(%1,%2)").arg(maxX).arg(minX));

        double maxY = qui.getMaxY()*0.01;
        double minY = qui.getMinY()*0.01;
        ui->labelYValue->setText(QString("(%1,%2)").arg(maxY).arg(minY));
    }
    else if(suffix == "QUIX")
    {
        DataFileQuix quix;
        quix.initFile(filePath);
        quix.convertDataToEmbAbs();

        ui->labelPatternNameValue->setText(fileName);
        ui->labelTotalNeedleValue->setText(QString::number(quix.getStitchNums()));

        double width = quix.getDatWidth()*0.01;
        ui->labelPatternWidthValue->setText(QString("%1").arg(width));

        double height = quix.getDatHeight()*0.01;
        ui->labelPatternHeightValue->setText(QString("%1").arg(height));

        double maxX = quix.getMaxX()*0.01;
        double minX = quix.getMinX()*0.01;
        ui->labelXValue->setText(QString("(%1,%2)").arg(maxX).arg(minX));

        double maxY = quix.getMaxY()*0.01;
        double minY = quix.getMinY()*0.01;
        ui->labelYValue->setText(QString("(%1,%2)").arg(maxY).arg(minY));
    }
    else if(suffix == "PLT")
    {
    }
    else if(suffix == "DXF")
    {
    }

    //qDebug()<<"get patternpara begin";
}

//设置类型图标
void PatternSelectWidget::setTypeLogo(QString tStyle)
{
    ui->buttonTypeLogo->setUnPreBtnLogo(tStyle);
}

//设置主title
void PatternSelectWidget::setMainTitle(QString str)
{
    ui->labelMainTitle->setText(str);
}

//设置副title
void PatternSelectWidget::setSubTitle(QString str)
{
    ui->labelSubTitle->setText(str);
}

//生成当前路径花样
void PatternSelectWidget::createCurDirPatterns()
{
    m_fileItemList.clear();
    QDir dir(m_curFilePath);

    // 打开文件所在的路径
    if(!dir.exists())
    {
        m_curPages = 0;
        m_pageNums = 0;
        qDebug() << "dirpath not exist, name=" << m_curFilePath;

        dir.mkdir(m_curFilePath);//创建花样文件夹
    }

    QString fileName;
    QString filePath;
    FileItem item;

    dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoDotAndDotDot);  // 设置类型过滤器，只为文件夹和文件格式
    dir.setSorting(QDir::DirsFirst | QDir::IgnoreCase);  // 设置排序方式

    QFileInfoList fileList = dir.entryInfoList();
    int count = fileList.count();

    for(int i = 0; i < count; i++)
    {
        QImage image(QSize(ui->buttonImage1->labelImage->width(), ui->buttonImage1->labelImage->height()), IMAGE_TYPE);
        QFileInfo fileInfo = fileList[i];

        if(fileInfo.isDir())//为文件夹
        {
            filePath = fileInfo.absoluteFilePath();
            fileName = fileInfo.baseName();
            //QString imageName = ":/images/folder.png";
            if(g_emResolut == resolution1006)
            {
                image.load(":/images/folder.png");
            }
            else if(g_emResolut == resolution1910)
            {
                image.load(":/images/folderBig.png");
            }
            if(g_emResolut == resolution0804)
            {
                image.load(":/images/folder.png");
            }
            item.setFileInfo(filePath,fileName,image);
            m_fileItemList.append(item);
        }
        else//为文件
        {
            filePath = fileInfo.absoluteFilePath();
            fileName = fileInfo.fileName();
            QString imageName = filePath + ".preview.png";
            QFile imageFile(imageName);

            if(fileInfo.suffix().toUpper() == "DST")//为dst文件
            {
                //排除机型
                if(g_emMacType == MACHINE_FIVEHEADPRECISIONSEWING
                        || g_emMacType == MACHINE_FLATCUTTINGMAC
                        || g_emMacType == MACHINE_DRAWING
                        || g_emMacType == MACHINE_FLYFLATCUTTING)
                    continue;

                if(!imageFile.exists())//图片不存在时生成图片
                {
                    DataFileDst dst;
                    //重新改变图片大小，因为文件夹的图标大小与图片大小不同
                    dst.initFile(filePath);
                    dst.createPreviewImage(&image, 1, PEN_WIDTH);// 生成预览文件
                }
                else
                {
                    image.load(imageName);
                }
                item.setFileInfo(filePath,fileName,image);
                m_fileItemList.append(item);
            }
            else if(fileInfo.suffix().toUpper() == "DSR")//dsr文件
            {
                //排除机型
                if(g_emMacType == MACHINE_FLATCUTTINGMAC
                        || g_emMacType == MACHINE_DRAWING
                        || g_emMacType == MACHINE_FLYFLATCUTTING)
                    continue;

                if(!imageFile.exists())//图片不存在时生成图片
                {
                    DataFileDsr dsr;
                    dsr.initFile(filePath);
                    dsr.createPreviewImage(&image, 1, PEN_WIDTH);// 生成预览文件
                }
                else
                {
                    image.load(imageName);
                }
                item.setFileInfo(filePath,fileName,image);
                m_fileItemList.append(item);
            }
            else if(fileInfo.suffix().toUpper() == "QUI")
            {
                //排除机型
                if(g_emMacType == MACHINE_FIVEHEADPRECISIONSEWING
                        || g_emMacType == MACHINE_FLATCUTTINGMAC
                        || g_emMacType == MACHINE_FLYFLATCUTTING
                        || g_emMacType == MACHINE_DRAWING
                        || g_emMacType == MACHINE_THICK_WIRING)
                    continue;

                if(!imageFile.exists())//图片不存在时生成图片
                {
                    DataFileQui qui;
                    qui.initFile(filePath);
                    qui.createPreviewImage(&image, 1, PEN_WIDTH);// 生成预览文件
                }
                else
                {
                    image.load(imageName);
                }
                item.setFileInfo(filePath,fileName,image);
                m_fileItemList.append(item);
            }
            else if(fileInfo.suffix().toUpper() == "QUIX")
            {
                //排除机型
                if(g_emMacType == MACHINE_FIVEHEADPRECISIONSEWING
                        || g_emMacType == MACHINE_FLATCUTTINGMAC
                        || g_emMacType == MACHINE_FLYFLATCUTTING
                        || g_emMacType == MACHINE_DRAWING
                        || g_emMacType == MACHINE_THICK_WIRING)
                    continue;
                if(!imageFile.exists())//图片不存在时生成图片
                {
                    DataFileQuix quix;
                    quix.initFile(filePath);
                    quix.createPreviewImage(&image, 1, PEN_WIDTH);// 生成预览文件
                }
                else
                {
                    image.load(imageName);
                }
                item.setFileInfo(filePath,fileName,image);
                m_fileItemList.append(item);
            }
            else if(fileInfo.suffix().toUpper() == "PLT")
            {
                //排除机型
                if(g_emMacType == MACHINE_FIVEHEADPRECISIONSEWING
                        || g_emMacType == MACHINE_THICK_WIRING)
                    continue;
                if(!imageFile.exists())//图片不存在时生成图片
                {
                    ImportHPGL importHPGL;
                    //判断是否为加密文件
                    if (importHPGL.IsSecretFile(filePath) == true)
                    {
                        // 文件路径
                        QDir apppath(qApp->applicationDirPath());
                        QString strSecretFile = apppath.path() + apppath.separator() + "Secret.plt";

                        importHPGL.BitMapDtat(filePath,strSecretFile);
                        importHPGL.IniPara();
                        importHPGL.ReadSecretFile(strSecretFile);
                    }
                    else
                    {
                        importHPGL.IniPara();
                        importHPGL.Read(filePath);
                    }
                    importHPGL.createPreviewImage(&image, 1, PEN_WIDTH);// 生成预览文件
                }
                else
                {
                    image.load(imageName);
                }
                item.setFileInfo(filePath,fileName,image);
                m_fileItemList.append(item);
            }
            else if(fileInfo.suffix().toUpper() == "DXF") {

                qDebug() << "Reading file.....\n";

                //适用机型
                if(g_emMacType != MACHINE_FLYFLATCUTTING)
                    continue;

                dxf_tools_inst->fun_clean_all();
                qDebug() << "Reading file " << filePath.toStdString().c_str() << "...\n";          \
                hank_CreationClass* creationClass  = new hank_CreationClass() ;
                //                hank_CreationClass creationClass ;
                hank::DL_Dxf dxf ;
                //   hank::DL_Dxf* dxf = new hank::DL_Dxf() ;
                std::string file_path = filePath.toStdString();
                char *file_path_c = (char *)file_path.c_str();

                // 指定要读取的文件名
                std::string filename =  file_path_c ;

                // 打开文件
                std::ifstream file(filename);

                // 检查文件是否成功打开
                if (!file.is_open()) {
                    std::cerr << "无法打开文件: " << filename << std::endl;
                    return  ;
                }

                // 创建 stringstream 对象
                std::stringstream ssbuffer;


                if(file_path.length()<=0) {

                } else if (!dxf.in(ssbuffer, creationClass)) { // if file open failed
                    qDebug() << "error \n";
                }else{
                    qDebug() << "ok \n";
                }
                //                delete dxf;
                delete creationClass;

                qDebug() << "Reading file ...end\n size:"<<dxf_tools_inst->m_all_info.size();
                for (   auto it : dxf_tools_inst->m_all_info) {
                    qDebug()<<"secnod size:"<<it.second.size();
                    for (  auto  sp_item : it.second ) {
                        sp_item->fun_show();
                    }
                }
            }
        }
    }

    QString dirPath = m_curFilePath;// 当前路径
    QString desiredPath = "";
    // 查找关键路径节点位置
    int dataPos = dirPath.indexOf("/datafiles");
    if (dataPos != -1) {
        // 截取并替换斜杠
        desiredPath = dirPath.mid(dataPos + 10)
                .replace("/", " > "); // 关键替换操作
    }
    ui->labelSubTitle->setText(tr("Pattern setting > Pattern selection") + desiredPath);

    refreshPageUi();
    refreshChecked();
}

//获取绘图区域大小
QSize PatternSelectWidget::getImageSize()
{
    QSize size = ui->buttonImage1->labelImage->size();
    return size;
}

void PatternSelectWidget::on_buttonImage1_clicked()
{
    clickItem(1);
}

void PatternSelectWidget::on_buttonImage2_clicked()
{
    clickItem(2);
}

void PatternSelectWidget::on_buttonImage3_clicked()
{
    clickItem(3);
}

void PatternSelectWidget::on_buttonImage4_clicked()
{
    clickItem(4);
}

void PatternSelectWidget::on_buttonImage5_clicked()
{
    clickItem(5);
}

void PatternSelectWidget::on_buttonImage6_clicked()
{
    clickItem(6);
}

void PatternSelectWidget::on_buttonImage7_clicked()
{
    clickItem(7);
}

void PatternSelectWidget::on_buttonImage8_clicked()
{
    clickItem(8);
}

void PatternSelectWidget::on_buttonImage9_clicked()
{
    clickItem(9);
}

void PatternSelectWidget::on_buttonImage10_clicked()
{
    clickItem(10);
}

void PatternSelectWidget::on_buttonBackUpDir_clicked()
{
    if(m_curFilePath.size() <= 0)
    {
        return;
    }

    QDir dir(m_curFilePath);
    dir.cdUp();//返回上级目录
    QString path = dir.absolutePath();//得到上级目录
    m_fileItemList.clear();
    m_selectedPattenIdx = -1;
    getDirPatternFiles(path);//打开上级目录
}

void PatternSelectWidget::on_buttonPgUp_clicked()
{
    m_curPages--;
    refreshPageUi();
}

void PatternSelectWidget::on_buttonPgDn_clicked()
{
    m_curPages++;
    refreshPageUi();
}

void PatternSelectWidget::on_buttonOk_clicked()
{
    if(m_selectedPattenIdx < 0)
    {
        return;
    }

    int patternNeedles = ui->labelTotalNeedleValue->text().toInt();
    if(patternNeedles > EMBALLOWNEEDLELIMIT)//大于200万针
    {
        PromptDialog promptDlg(this);
        promptDlg.initDialog(PromptDialog::BTN_OK);
        promptDlg.setTitleStr(tr("Prompt"));

        QString str;
        //所选花样针数已达上限(200万针)，不可绣作！
        str = tr("The number of stitches of the selected pattern has reached the upper limit (2 million stitches), and it cannot be embroidered!");
        promptDlg.setContentStr(str);

        promptDlg.exec();
        return;
    }
    emit siSelectPattern(m_fileItemList.at(m_selectedPattenIdx).getFilePath());

    //this->hide();
}

void PatternSelectWidget::on_buttonCancel_clicked()
{
    this->hide();
}

void PatternSelectWidget::mousePressEvent(QMouseEvent *e)
{
    if ( e->button() == Qt::LeftButton)
    {
        m_mousePressX = e->x();
        m_mousePressY = e->y();
        m_mouseReleaseX = 0;
        m_mouseReleaseY = 0;
    }
}

void PatternSelectWidget::mouseReleaseEvent(QMouseEvent *e)
{
    if ( e->button() == Qt::LeftButton)
    {
        m_mouseReleaseX = e->x();
        m_mouseReleaseY = e->y();
    }

    int width = this->width();
    int height = this->height();
    if ((m_mousePressX >= 0 && m_mousePressX <= 100)  &&
            ((m_mousePressY >= (height - 100)) && m_mousePressY <= height) &&
            ((m_mouseReleaseX >= (width - 100)) && m_mouseReleaseX <= width) &&
            ((m_mouseReleaseY >= (height - 100)) && m_mouseReleaseY <= height))
    {
        MainWidgetFunction mainFunction;
        QString usbPath;//优盘路径
        usbPath = mainFunction.detectUsb();//优盘检测
        if(usbPath.length() <= 0)
        {
            //优盘不存在
            return;
        }
        else
        {
            QPixmap pixmap=QPixmap::grabWindow(this->winId(),0,0,this->width(),this->height());//截屏存放在pixmap
            QString name_pc = usbPath +  "EMB" + //
                    QDateTime::currentDateTime().toString("yyyyMMdd") +//获取时期时间
                    +"_"+
                    QDateTime::currentDateTime().toString("hhmmss")    + ".png";

            pixmap.save(name_pc,"png"); // 路径
        }
    }

    m_mousePressX = 0;
    m_mousePressY = 0;
    m_mouseReleaseX = 0;
    m_mouseReleaseY = 0;
}
